//
//  AccountController.m
//  whopaidforit
//
//  Created by Hoang Vu on 1/28/13.
//  Copyright (c) 2013 Hoang Vu. All rights reserved.
//

#import "AccountController.h"

@interface AccountController ()<UITextFieldDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate>

@end


@implementation AccountController

@synthesize changePhoto, photo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}
-(void)createAccountView
{
    self.accountLabel =[[UILabel alloc]initWithFrame:CGRectMake(5, 60, 100, 30)];
    self.accountLabel.text=@"Account";
    [self.view addSubview:self.accountLabel];
    
    self.accountView =[[UIView alloc]initWithFrame:CGRectMake(5, 90, 310, 230)];
    [StyleControl setBorderStyle:(UIImageView *)self.accountView];
    [self.view addSubview: self.accountView];
    
    
    //----
    self.profilePhoto=[[UILabel alloc]initWithFrame:CGRectMake(5, 10, 100, 30)];
    self.profilePhoto.text=@"ProFieldFoto";
    self.profilePhoto.textAlignment= NSTextAlignmentLeft;
    [self.accountView addSubview:self.profilePhoto];
    [self.profilePhoto release];
    
    
    self.profileImageView =[UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.profileImageView.frame=CGRectMake(250, 5, 50, 45);
    [self.accountView addSubview:self.profileImageView];
    [self.profileImageView addTarget:self action:@selector(ChangePhoto:) forControlEvents:UIControlEventTouchUpInside];
    
    //----------
    self.name=[[UILabel alloc]initWithFrame:CGRectMake(5, 60, 200, 30)];
    self.name.text=@"Voornaam";
    self.name.textAlignment= NSTextAlignmentLeft;
    [self.accountView addSubview:self.name];
    [self.name release];
    
    self.nameField =[[UITextField alloc ]initWithFrame:CGRectMake(110, 65, 200, 30)];
    [self.nameField setBackgroundColor:[UIColor brownColor]];
    [self.accountView addSubview:self.nameField];
    [self.nameField release];
    
    //----------
    self.eMail=[[UILabel alloc]initWithFrame:CGRectMake(5, 100, 100, 30)];
    self.eMail.text=@"Email";
    self.eMail.textAlignment= NSTextAlignmentLeft;
    [self.accountView addSubview:self.eMail];
    [self.eMail release];
    
    self.eMailField =[[UITextField alloc ]initWithFrame:CGRectMake(110, 105, 200, 30)];
    [self.eMailField setBackgroundColor:[UIColor brownColor]];
    [self.accountView addSubview:self.eMailField];
    [self.eMailField release];
    
    //----------
    self.pass=[[UILabel alloc]initWithFrame:CGRectMake(5, 140, 100, 30)];
    self.pass.text=@"Wachtwoord";
    self.pass.textAlignment= NSTextAlignmentLeft;
    [self.accountView addSubview:self.pass];
    [self.pass release];
    
    self.passField =[[UITextField alloc ]initWithFrame:CGRectMake(110, 145, 200, 30)];
    [self.passField setBackgroundColor:[UIColor brownColor]];
    self.passField.delegate = self;
    [self.accountView addSubview:self.passField];
    [self.passField release];
    
    //----------
    self.confirmPass=[[UILabel alloc]initWithFrame:CGRectMake(5, 175, 300, 60)];
    self.confirmPass.text=@"Herhaal \nWachtwoord";
    self.confirmPass.lineBreakMode = UILineBreakModeWordWrap;
    [self.confirmPass setNumberOfLines:2];
    
    self.confirmPass.textAlignment= NSTextAlignmentLeft;
    [self.accountView addSubview:self.confirmPass];
    [self.confirmPass release];
    
    self.confirmPassField =[[UITextField alloc ]initWithFrame:CGRectMake(110, 185, 200, 40)];
    [self.confirmPassField setBackgroundColor:[UIColor brownColor]];
    self.confirmPassField.delegate = self;
    [self.accountView addSubview:self.confirmPassField];
    [self.confirmPassField release];
}

-(void)logOut
{
    AppDelegate *appdelegate =[[UIApplication sharedApplication]delegate];
    // restar face
    appdelegate.isFace=-1;
    [appdelegate.imageDataArray removeAllObjects];
    [appdelegate.imageUrlArray removeAllObjects];
    
        ///detroy NSuser default  
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict)
    {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];
    
    // close facebook session
    [FBSession.activeSession closeAndClearTokenInformation];
    [[FBSession activeSession] close];
    Login *detail = [[Login alloc] init];
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
      
}
-(void)createLogOutView
{
    self.logOutButton =[UIButton buttonWithType:UIButtonTypeCustom];
    self.logOutButton.frame =CGRectMake(5, 345, 310, 30);
    [self.view addSubview:self.logOutButton];
    [StyleControl setBorderStyle:(UIImageView *)self.logOutButton];
    [self.logOutButton addTarget:self action:@selector(logOut) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.imgOut =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    self.imgOut.image=[UIImage imageNamed:@"logOut"];
    [self.logOutButton addSubview:self.imgOut];
    [self.imgOut release];
    
    self.textOut =[[UILabel alloc]initWithFrame:CGRectMake(40, 0, 200, 30)];
    self.textOut.text =@"Log uit";
    [self.logOutButton addSubview:self.textOut];
    
}

-(void)createConnect
{
    AppDelegate *appdelegate=[[UIApplication sharedApplication]delegate];
    if(appdelegate.isFace!=1)
    {
    FBLoginView *loginview = [[FBLoginView alloc] init];
    loginview.frame = CGRectMake(20, 400, 280, 40);
    loginview.delegate = self;
        
    
    for (id obj in loginview.subviews)
    {
        if ([obj isKindOfClass:[UIButton class]])
        {
            UIButton * loginButton =  obj;
            [loginButton setFrame:CGRectMake(0, 0, 280, 40)];
            loginButton.tag=1012;
            
            UIImage *loginImage = [UIImage imageNamed:@"signWithFace"];
            [loginButton setImage:loginImage forState:UIControlStateNormal];
            [loginButton setBackgroundImage:nil forState:UIControlStateHighlighted];
            if(appdelegate.isFace==1)
            {
            [loginButton setHidden:YES];
            }
        }
        if ([obj isKindOfClass:[UILabel class]])
        {
            UILabel * loginLabel =  obj;
            [loginview setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0]];
            loginLabel.textAlignment = UITextAlignmentCenter;
            [loginLabel setFrame:CGRectMake(0, 0, 0, 0)];
            
        }
    }
    [self.view addSubview:loginview];

    }
    UIButton * connectButton =  [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [connectButton setFrame:CGRectMake(20, 400, 280, 40)];
    
    
    
    UIImage *loginImage = [UIImage imageNamed:@"signWithFace"];
    [connectButton setImage:loginImage forState:UIControlStateNormal];
    [connectButton setBackgroundImage:nil forState:UIControlStateHighlighted];
    connectButton.tag =1013;
    [connectButton addTarget:self action:@selector(dataRestore)forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:connectButton];
    if(appdelegate.isFace !=1)
    {
        [connectButton setHidden:YES];
    }
}

-(void)synchInformationWithFace
{
    
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user
{
    
    UIButton *buttton =(UIButton *)[self.view viewWithTag:1012];
    [buttton setHidden:YES];
    
    UIButton *buttton1 =(UIButton *)[self.view viewWithTag:1013];
    [buttton1 setHidden:NO];
    AppDelegate *appdelegate =[[UIApplication sharedApplication]delegate];
    appdelegate.isFace=1;
    [appdelegate.imageDataArray removeAllObjects];
    [appdelegate.imageUrlArray removeAllObjects];
    
    UserClass *unit =[[UserClass alloc]init];
    unit.userName=[user.first_name stringByAppendingString:[NSString stringWithFormat:@"%@",user.last_name]];
    unit.userId=user.id;
    unit.userEmail=[user.id stringByAppendingString:@"@facebook.com"];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:unit.userName forKey:@"userName"];
    [defaults setObject:unit.userId forKey:@"userId"];
    [defaults setObject:unit.userEmail forKey:@"userEmail"];
    [self dataRestore];
    
     FBRequest* friendsRequest = [FBRequest requestForMyFriends];
    [friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
                                                  NSDictionary* result,
                                                  NSError *error) {
        NSArray* friends = [result objectForKey:@"data"];
        [defaults setObject:friends forKey:@"friendList"];
        
    }];
    
}

-(void)dataRestore
{
    User *user = [User instance];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.nameField.text =[defaults objectForKey:@"userName"];
    //self.eMailField.text=[defaults objectForKey:@"userEmail"];
    self.passField.text= @"";
    self.confirmPassField.text=@"";
    changePhoto = YES;
    user.photo = @"facebook";
    NSString *urlString = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture",[defaults objectForKey:@"userId"]];
    NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: urlString]];
    UIImage *image = [[UIImage alloc] initWithData:imageData];
    [self.profileImageView setBackgroundImage:image forState:UIControlStateNormal];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if(textField==self.confirmPassField || textField == self.passField)
    {
        CGRect contentFrame;
        contentFrame = self.view.frame;
        contentFrame.origin.y=-40;
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        self.view.frame=contentFrame;
        [UIView commitAnimations];
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    CGRect contentFrame;
    contentFrame = self.view.frame;
    if(contentFrame.origin.y==-40)
    {
        contentFrame.origin.y=20;
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        self.view.frame=contentFrame;
        [UIView commitAnimations];
        [textField resignFirstResponder];
    }
    [textField resignFirstResponder];
    return YES;
}

-(void)createContent
{
    [self createAccountView];
    [self createLogOutView];
    [self createConnect];
    [self labelStyle];
    [StyleControl background:self.view];
}

-(void)labelStyle
{
    [self.accountLabel setBackgroundColor:[UIColor clearColor]];
    [self.profilePhoto setBackgroundColor:[UIColor clearColor]];
    [self.name setBackgroundColor:[UIColor clearColor]];
    [self.pass setBackgroundColor:[UIColor clearColor]];
    [self.eMail setBackgroundColor:[UIColor clearColor]];
    [self.confirmPass setBackgroundColor:[UIColor clearColor]];
    [self.textOut setBackgroundColor:[UIColor clearColor]];

    
    [self.nameField setBackgroundColor:[UIColor clearColor]];
    [self.passField setBackgroundColor:[UIColor clearColor]];
    [self.confirmPassField setBackgroundColor:[UIColor clearColor]];
    [self.eMailField setBackgroundColor:[UIColor clearColor]];
    
    [StyleControl drawLine:self.accountView PositionX:0 PositionY:55 Width:310];
    [StyleControl drawLine:self.accountView PositionX:0 PositionY:95 Width:310];
    [StyleControl drawLine:self.accountView PositionX:0 PositionY:135 Width:310];
    [StyleControl drawLine:self.accountView PositionX:0 PositionY:175 Width:310];

    self.nameField.delegate=self;
    self.passField.delegate=self;
    self.confirmPassField.delegate=self;
    self.eMailField.delegate=self;
    [StyleControl setBorderStyle:(UIImageView *)self.profileImageView];    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.photo = [[NSString alloc] init];
    [self createNavigation];
    [self createContent];
    [self loadData];
    [self createImageLocation];
    
}
-(void)createImageLocation
{

        NSError *error ;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/AppImages"];
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
            [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
    

- (void)saveImage:(UIImage*)image andName :(NSString*)imageName
{
    NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
    
    NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
    
    NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
    
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/AppImages"];
    NSString *fullPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];
    
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally 
    
}

-(void) createNavigation
{
    UIButton *left =[UIButton buttonWithType:UIButtonTypeCustom];
    UIButton *right =[UIButton buttonWithType:UIButtonTypeCustom];
    [left setTitle:@"Vorige" forState:UIControlStateNormal];
    [right setTitle:@"Opslaan" forState:UIControlStateNormal];
    left.frame = CGRectMake(8, 8, 80, 30);
    right.frame = CGRectMake(235, 8, 80, 30);
    
    NSString *title = [NSString stringWithFormat:NSLocalizedString(@"account.title", @"")];
    [left addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [right addTarget:self action:@selector(saveAccount) forControlEvents:UIControlEventTouchUpInside];
    [StyleControl naviStyle:self.view andTitle:title andColor:1 andleftButton:left andRightButton:right borderLeft:1 borderRight:1];
}
-(void) loadData
{
    UserClass *info = [[UserClass alloc] init];
    User *user = [User instance];
    info = [user getAccountWS:user._id];
    user.photo = info.photo;
    changePhoto = NO;
    
    self.nameField.text = info.userName;
    self.eMailField.text = info.userEmail;
    self.passField.text = info.password;
    self.confirmPassField.text = info.password;
    if(![info.photo isEqualToString:@""] ){
        //-------load image in app locatio
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
        
        NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
        
        NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/AppImages"];
        
        NSString *fullPath = [[dataPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d",user._id]] stringByAppendingString:@".png"];
        
        UIImage *imageTemp =[UIImage imageWithContentsOfFile:fullPath];
        [self.profileImageView setBackgroundImage:imageTemp forState:UIControlStateNormal];
    }else if([info.avatar isEqualToString:@""] && info.facebookid)
    {
        NSString *urlString = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture",info.facebookid];
        NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: urlString]];
        UIImage *image = [[UIImage alloc] initWithData:imageData];
        [self.profileImageView setBackgroundImage:image forState:UIControlStateNormal];
    }
    
}
-(void) back
{
    EventListController *detail = [[EventListController alloc] init];
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}
-(void) saveAccount
{
    User *user = [User instance];
    NSString *pass = [self.passField.text stringByTrimmingCharactersInSet:
                      [NSCharacterSet whitespaceCharacterSet]];
    NSString *conPass = [self.confirmPassField.text stringByTrimmingCharactersInSet:
                         [NSCharacterSet whitespaceCharacterSet]];
    if (![conPass isEqualToString:pass] ) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Account"
                                                        message:@"Gelieve voer het wachtwoord in en bevestig het paswoord."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    else{
        [user updateAccountWS:user._id Name:self.nameField.text Email:self.eMailField.text Password:self.passField.text Photo:user.photo];
        EventListController *detail = [[EventListController alloc] init];
        [self presentViewController:detail animated:YES completion:NULL];
        [detail release];
        [self saveImage:self.userImage andName:[NSString stringWithFormat:@"%d",user._id]];
    }
}

-(IBAction)ChangePhoto:(id)sender
{
    UIActionSheet *actionSheet= [[[UIActionSheet alloc]initWithTitle:@"Chose Photo" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Photo",@"Camera", nil]autorelease ];
    [actionSheet showInView:self.view ];
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex==0)
    {
        UIImagePickerController* picker= [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary ;
        [self presentViewController:picker animated:YES completion:nil];
        
    }
    else if(buttonIndex==1)
    {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = NO;
        [self presentModalViewController:imagePicker animated:YES];
    }
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    User *user = [User instance];
    user.photo = [NSString stringWithFormat:@"%d",user._id];
    changePhoto = YES;
    [picker dismissViewControllerAnimated:YES completion:nil];
    CGSize newSize ;
    newSize.height=100;
    newSize.width=120;
    
    UIGraphicsBeginImageContext(newSize);
    [[info objectForKey:@"UIImagePickerControllerOriginalImage"] drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    self.userImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.profileImageView setBackgroundImage:self.userImage forState:UIControlStateNormal];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
